import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '@common/database/entity/user.entity';

import { ApiFail } from '@common/utils';
import { SysConfig } from '@common/database/entity/sys_config.entity';
import { ChargeRecord } from '@common/database/entity/charge_record.entity';

@Injectable()
export class AuthService {
  constructor(
    @Inject('USER_REPOSITORY')
    public readonly repo: Repository<User>,
    @Inject('SYS_CONFIG_GREPOSITORY')
    public readonly sysConfigRepo: Repository<SysConfig>,
    @Inject('CHARGE_RECORD_GREPOSITORY')
    public readonly chargeRecordRepo: Repository<ChargeRecord>,
  ) {}

  
  //获取会员id
  async getUser(opendId: string) {
    const user:User = await this.repo
      .createQueryBuilder('user')
      // "id,mobile,userName,weixin_openId,nickName,avatar,is_new"
      .select([
        'user.id',
        'user.bid',
        'user.weixin_openId',
        'user.nickName',
        'user.avatar',
        'user.is_new',
        'user.amount',
      ]) // 查询 id 和 username
      .where('(user.weixin_openId=:id)', { id: opendId })
      .getOne();
    return user;
  }

  //添加一个用户
  async add(user: User) {
    return await this.repo.insert(user);
  }
  async update(user) {
    return await this.repo.update({ weixin_openId: user.weixin_openId }, user);
  }
  async getSysConfig(isFree) {
    return await this.sysConfigRepo.findOne({ where: { name: isFree } });
  }
  async addChargeRecord(charge_record) {
    return await this.chargeRecordRepo.insert(charge_record);
  }

  async updateChargeRecord(charge_record) {
    return await this.chargeRecordRepo.update(
      { userId: charge_record.userId },
      charge_record,
    );
  }
}
